<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>默认Iterator接口</title>
</head>
<body>
    <h1>默认Iterator接口</h1>
    <h2>Symbol.iterator属性指向默认的遍历器生成函数</h2>

    <script>
        // 为对象添加Iterator接口
        const myObject = {
            data: ['hello', 'world'],
            [Symbol.iterator]() {
                const self = this;
                let index = 0;
                return {
                    next() {
                        if (index < self.data.length) {
                            return {
                                value: self.data[index++],
                                done: false
                            };
                        }
                        return { value: undefined, done: true };
                    }
                };
            }
        };

        // 使用for...of遍历
        for (let value of myObject) {
            console.log(value); // 'hello' 'world'
        }

        // 类似数组的对象部署Iterator接口
        const arrayLike = {
            0: 'a',
            1: 'b',
            2: 'c',
            length: 3,
            [Symbol.iterator]: Array.prototype[Symbol.iterator]
        };

        for (let item of arrayLike) {
            console.log(item); // 'a' 'b' 'c'
        }

        // 检测是否有Iterator接口
        console.log(typeof myObject[Symbol.iterator]); // "function"
        console.log(typeof Array.prototype[Symbol.iterator]); // "function"
        console.log(typeof Set.prototype[Symbol.iterator]); // "function"
        console.log(typeof Map.prototype[Symbol.iterator]); // "function"
    </script>
</body>
</html> 